import axios from 'axios'
import errorCode from './errorCode'
import { getToken } from './auth'
import {Message, MessageBox} from 'element-ui'
// import el from 'element-ui/src/locale/lang/el'
// 默认请求头
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
let baseURL = process.env.BASE_API

const service = axios.create({
  baseURL: baseURL,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
  },
  timeout: 10000
})

service.interceptors.request.use(configs => {
  // 是否需要设置token
  const isToken = (configs.headers || {}).isToke === false
  if (getToken() && !isToken) {
  // 让每个请求请求携带自定义token，请根据实际情况自行修订
    configs.headers['Authorization'] = 'Bearer' + ' ' + getToken()
  }
  return configs
},
error => {
  console.log(error)
  Promise.reject(error)
})

service.interceptors.response.use(res => {
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200
  // 获取错误信息
  const message = errorCode[code] || res.data.msg || errorCode['default']
  if (code === 401) {
    MessageBox.confirm(
      '登录状态已过期，您可以继续留在该页面，或者重新登录',
      '系统提示',
      {
        confirmButtonText: '请重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      console.log('登录失败')
    })
  } else if (code === 500) {
    Message({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  } else if (code !== 200) {
    Notification.error({
      title: message
    })
  } else {
    return res.data
  }
}, error => {
  console.log('err' + error)
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
})

export default service
